package com.gcloud.mesh.dcs.chain.ali;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.smc20190601.Client;
import com.aliyun.smc20190601.models.*;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.dcs.chain.MigrationConstant;
import com.gcloud.mesh.dcs.dao.SchedulerStepDao;
import com.gcloud.mesh.dcs.entity.SchedulerStepEntity;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.MyBusinessException;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

//@Component
@Slf4j
public class StartReplicationJob_5 extends AbstractAliMigrationStep {

    @Autowired
    private SchedulerStepDao schedulerStepDao;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        String accessKeyId = jsonObject.getString("accessKeyId");
        String accessSecret = jsonObject.getString("accessSecret");
        String jobId = jsonObject.getString("jobId");
        Client client = super.createSMCClient(accessKeyId,accessSecret);
        this.startReplicationJob(client,jobId);
        filterChain.doExec(schedulerJobId,jsonObject.toString(),filterChain,stepChain);
    }

    @Override
    public boolean checkStatus(String stepId) {
        try {
            SchedulerStepEntity stepEntity = schedulerStepDao.getById(stepId);
            JSONObject json = JSONObject.parseObject(stepEntity.getAttach());
            String accessKeyId = json.getString("accessKeyId");
            String accessSecret = json.getString("accessSecret");
            String jobId = json.getString("jobId");
            String sourceId = json.getString("sourceId");
            DescribeReplicationJobsResponseBody.DescribeReplicationJobsResponseBodyReplicationJobsReplicationJob dd = this.describeReplicationJobs(accessKeyId, accessSecret, jobId, sourceId);
            boolean result =  dd == null ? false : ("Finished".equalsIgnoreCase(dd.getStatus()));
            if(result){
                json.put("imageId",dd.getImageId());
                redisUtil.set(MigrationConstant.ATTACH_KEY_EXEC+stepEntity.getSchedulerJobId(),json.toString(),24*60*60);
                schedulerStepDao.updateAttachBySchedulerJobId(stepEntity.getSchedulerJobId(),json.toString());
            }
            return result;
        }catch (Exception e){
            log.error("checkStatus",e);
            return false;
        }
    }

    @Override
    public boolean isSyncChain() {
        return false;
    }


    @Override
    public String chainName(String attach) {
        return "启动迁移任务";
    }

    @Override
    public int getOrder() {
        return 5;
    }

    public void startReplicationJob(Client client, String jobId){
        //创建API请求，并设置参数
        StartReplicationJobRequest request = new StartReplicationJobRequest();
        //迁移任务ID
        request.setJobId(jobId);
        //发送请求获取返回值或处理异常
        try {
            StartReplicationJobResponse response = client.startReplicationJob(request);
            log.debug(new Gson().toJson(response));
            log.debug("**********启动迁移任务**********");
        } catch (Exception e) {
            log.error("启动迁移任务失败",e);
            throw  new MyBusinessException("启动迁移任务失败"+"::"+e.getMessage());
        }
    }


    public DescribeReplicationJobsResponseBody.DescribeReplicationJobsResponseBodyReplicationJobsReplicationJob describeReplicationJobs(String accessKeyId, String accessKeySecret,String jobId_,String sourceId){

        //创建API请求，并设置参数
        DescribeReplicationJobsRequest request = new DescribeReplicationJobsRequest();
        //设置迁移任务的页码
        request.setPageNumber(1);
        //设置每页行数
        request.setPageSize(10);
        //设置迁移任务的名称
//        request.setName("MigrationTask");
        //设置迁移任务ID列表
        List<String> jobIds = new ArrayList<>();
        jobIds.add(jobId_);
        request.setJobId(jobIds);
        //设置迁移源ID列表
        List<String> sourceIds = new ArrayList<>();
        sourceIds.add(sourceId);
        request.setSourceId(sourceIds);

        //发送请求获取返回值或处理异常
        DescribeReplicationJobsResponse response = null;
        try {
            response = createSMCClient(accessKeyId, accessKeySecret).describeReplicationJobs(request);
            log.debug(new Gson().toJson(response));
            log.debug("**********查询迁移任务状态**********");
        } catch (Exception e) {
            log.error("查询迁移任务状态失败",e);
            throw  new MyBusinessException("查询迁移任务状态失败"+"::"+e.getMessage());
        }
        List<DescribeReplicationJobsResponseBody.DescribeReplicationJobsResponseBodyReplicationJobsReplicationJob> replicationJobList = response.getBody().getReplicationJobs().getReplicationJob();
        return (replicationJobList==null || replicationJobList.isEmpty())? null:replicationJobList.get(0);
    }
}
